import { encryptPassword } from '@peng_kai/kit/utils';

export * from './number';
export * from './path';
export * from './tg';

export const envs = {
  get isStaging() {
    return import.meta.env.MODE === 'staging';
  },
  get isDevelopment() {
    return import.meta.env.MODE === 'development';
  },
  get isProduction() {
    return import.meta.env.MODE === 'production';
  },
  get isTestHost() {
    const h = location.hostname;
    return h.includes('img.g9') || h.includes('localhost') || h.includes('127.0.0.1');
  },
  /** 包含 TgApp 和 TgH5 端 */
  get isTg() {
    return !!Telegram.WebApp.initData || !!(window as any).TelegramWebviewProxy;
  },
  get isTgApp() {
    return !!Telegram.WebApp.initData;
  },
  get isPwa() {
    const isStandalone = window.matchMedia('(display-mode: standalone)').matches;
    const isIOSStandalone = (window.navigator as any).standalone === true;
    return isStandalone || isIOSStandalone;
  },
  get isAndroid() {
    return /android/i.test(navigator.userAgent);
  },
  get isMobile() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i.test(navigator.userAgent);
  },
  get isIos() {
    return /iphone|ipad|ipod/i.test(navigator.userAgent);
  },
  get iosVersion() {
    const userAgent = window.navigator.userAgent;
    const iOS = /iP(hone|od|ad)/.test(userAgent);
    if (iOS) {
      const versionMatch = userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
      if (versionMatch) {
        const major = Number.parseInt(versionMatch[1], 10);
        const minor = Number.parseInt(versionMatch[2], 10);
        return Number.parseFloat(`${major}.${minor}`);
      }
    }

    return null;
  },
  get inIframe() {
    return window !== window.top;
  },
};

/**
 * 获取 cookie 值
 */
export function getCookieValue(cookieName: string) {
  const cookieEntries = document.cookie.split('; ').map(item => item.split('='));
  const cookieObj = Object.fromEntries(cookieEntries);

  return cookieObj[cookieName];
}
/**
 * 检查cookie是否有指定key
 */
export function hasCookieName(cookieName: string) {
  const cookieEntries = document.cookie.split('; ').map(item => item.split('='));
  const cookieObj = Object.fromEntries(cookieEntries);
  return Object.prototype.hasOwnProperty.call(cookieObj, cookieName);
}

export function setCookie(cookieName: string, cookieValue: string) {
  const date = new Date();
  date.setTime(date.getTime() + (999999999999999 * 24 * 60 * 60 * 1000));
  const expires = `expires=${date.toUTCString()}`;
  document.cookie = `${cookieName}=${cookieValue}; ${expires}; path=/`;
}

/**
 * 创建表单验证结果
 * @param msg 失败的消息，如果为 true 则表示成功，默认为 true
 */
export function formResult(msg: true | string = true) {
  return msg === true ? Promise.resolve() : Promise.reject(new Error(String(msg)));
}

export function installWebApp(successCallback?: () => void, cancalCallback?: () => void) {
  // 检测环境
  if (envs.isPwa) {
    return;
  }

  // 显示安装提示
  window?.deferredPrompt?.prompt();
  // 等待用户选择
  window?.deferredPrompt?.userChoice?.then((choiceResult: any) => {
    if (choiceResult.outcome === 'accepted') {
      successCallback?.();
    }
    else {
      cancalCallback?.();
    }
    window.deferredPrompt = null;
  });
}

/**
 * 检测环境
 * @returns boolean
 */
export function isCanDownloadApp() {
  return !!window.deferredPrompt;
}

/** 密码加密 */
export function flzxsqc(lb: string) {
  return encryptPassword(lb, [
    'navigator.languaga',
    'confirm.execute',
    'location.exit',
    'document.cookle',
  ]);
}
